<template>
  <div class="roles">
    <!-- 面包屑 -->
     <el-row>
      <el-col :span="24">
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>角色管理</el-breadcrumb-item>
          <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>
      </el-col>
    </el-row>
    <!-- 添加按钮 -->
    <el-button type="primary" plain @click='addRoles'>添加角色</el-button>
    <!-- 展开表格 -->
     <el-table
      class="mt-15 mb-15"
      border
      :data="roleList"
      style="width: 100%">
      <!-- 添加type="expand"可以展开表格数据行 -->
      <el-table-column type="expand">
        <!-- 标签展示页 -->
       <template slot-scope="scope">
         <el-row v-for='(firstItem,index) in scope.row.children' :key="index">
          <el-col :span="4">
            <el-tag class="el-margin" closable
            @close='delRights(scope.row,firstItem.id)'>{{firstItem.authName}}</el-tag><i class="el-icon-arrow-right" v-if='firstItem.children.length!==0'></i>
          </el-col>
          <el-col :span="20">
            <el-row v-for='(secondItem,index) in firstItem.children' :key='index'>
              <el-col :span="4">
                <el-tag type="success" class="el-margin" closable
                 @close='delRights(scope.row,secondItem.id)'>{{secondItem.authName}}</el-tag>
                <i class="el-icon-arrow-right" v-if='secondItem.children.length!==0'></i>
              </el-col>
              <el-col :span="20">
                 <el-tag type="warning" v-for='(threeItem,index) in secondItem.children' :key='index' class="el-margin" closable  @close='delRights(scope.row,threeItem.id)'>{{threeItem.authName}}</el-tag>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
       </template>
      </el-table-column>
      <el-table-column
          type="index"
          width="50">
      </el-table-column>
      <el-table-column
        label="角色名称"
        prop="roleName"
        >
      </el-table-column>
      <el-table-column
        label="描述"
        prop="roleDesc">
      </el-table-column>
      <el-table-column
        label="操作">
        <template slot-scope="scope">
          <el-button size="mini" icon="el-icon-edit" plaintype="primary" @click='eidtRoles(scope.row)'></el-button>
          <el-button size="mini" icon="el-icon-delete" plain type="danger" @click='delRoles(scope.row)'></el-button>
          <el-button size="mini" icon="el-icon-check" plain type="warning" @click='rolesRights(scope.row)'></el-button>
        </template>
      </el-table-column>
     </el-table>
     <!-- 添加角色框 -->
    <el-dialog title="添加角色" :visible.sync="rolesAddDialogFormVisible">
      <el-form :model="addform" :rules="rules" ref='rolesUserForm'>
        <el-form-item label="角色名称" :label-width="formLabelWidth" prop="roleName">
          <el-input v-model="addform.roleName" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" :label-width="formLabelWidth" prop="roleDesc">
          <el-input v-model="addform.roleDesc" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="rolesAddDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAddRolesUser('rolesUserForm')">确 定</el-button>
      </div>
    </el-dialog>
     <!-- 编辑角色框 -->
    <el-dialog title="编辑角色" :visible.sync="rolesEditDialogFormVisible">
      <el-form :model="editform" :rules="rules" ref='rolesUserForm'>
        <el-form-item label="角色名称" :label-width="formLabelWidth" prop="roleName">
          <el-input v-model="editform.roleName" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" :label-width="formLabelWidth" prop="roleDesc">
          <el-input v-model="editform.roleDesc" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="rolesEditDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEditRolesUser('rolesUserForm')">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 授权详细 -->
     <el-dialog title="角色授权" :visible.sync="rolesRightsDialogFormVisible">
      <el-tree
        ref='tree'
        :data="treeData"
        show-checkbox
        node-key='id'
        default-expand-all
        :default-checked-keys="selectedRights"
        :props="defaultProps">
        <!-- :default-checked-keys   默认勾选的节点的 key 的数组 -->
      </el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button @click="rolesRightsDialogFormVisible = false">取 消</el-button>
        <!-- 通过node获取选中节点 -->
        <el-button type="primary" @click='submitEditRoleRights'>确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import {
    getRoleList,
    addRoleList,
    delRoleList,
    editRoleList,
    getRightsList,
    delRoleRight,
    rolesGetRights
  } from "@/api";
  export default {
    data() {
      return {
        // 被选的所有权限id集合
        selectedRights: [],
        // 设置当前角色，接收当前角色的权限数据
        currentRole: "",
        // 添加弹框显示与隐藏
        rolesAddDialogFormVisible: false,
        // 编辑弹框显示与隐藏
        rolesEditDialogFormVisible: false,
        // 权限树显示与隐藏
        rolesRightsDialogFormVisible: false,
        formLabelWidth: "120px",
        roleList: [],
        // 添加用户的表单对象
        addform: {
          roleName: "",
          roleDesc: "",
          id: ""
        },
        // 编辑用户的表单对象
        editform: {
          roleName: "",
          roleDesc: "",
          id: ""
        },
        rules: {
          roleName: [
            { required: true, message: "请输入角色名", trigger: "blur" }
          ],
          roleDesc: [
            { required: true, message: "请输入角色描述", trigger: "blur" }
          ]
        },
        defaultProps: {
          children: "children",
          label: "authName"
        },
        treeData: []
      };
    },
    created() {
      this.initList();
    },
    methods: {
      // 初始化角色列表
      initList() {
        getRoleList().then(res => {
          // console.log(res);
          if (res.meta.status === 200) {
            this.roleList = res.data;
          }
        });
      },
      // 展示添加页面
      addRoles() {
        this.rolesAddDialogFormVisible = true;
      },
      // 角色添加完成
      submitAddRolesUser(formData) {
        this.$refs[formData].validate(valide => {
          if (valide) {
            addRoleList(this.addform).then(res => {
              console.log(res);
              if (res.meta.status === 201) {
                this.$message.success("角色添加成功");
                this.rolesAddDialogFormVisible = false;
                this.initList();
              } else {
                this.$message.error("角色添加失败");
              }
            });
          } else {
            console.log("表单数据填写不正确");
          }
        });
      },
      // 角色删除完成
      delRoles(row) {
        // console.log(row.id);
        this.$confirm("此操作将永久删除该角色, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(res => {
            delRoleList(row.id).then(res => {
              this.$message({
                type: "success",
                message: "删除成功!"
              });
              this.initList();
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除"
            });
          });
      },
      // 展示编辑页面
      eidtRoles(row) {
        this.rolesEditDialogFormVisible = true;
        this.editform.roleName = row.roleName;
        this.editform.roleDesc = row.roleDesc;
        this.editform.id = row.id;
      },
      // 角色编辑完成
      submitEditRolesUser(formData) {
        // 验证表单信息
        this.$refs[formData].validate(valide => {
          if (valide) {
            editRoleList(this.editform).then(res => {
              console.log(res);
              if (res.meta.status === 200) {
                this.$message.success("角色编辑成功");
                this.rolesEditDialogFormVisible = false;
                this.initList();
              } else {
                this.$message.error("角色编辑失败");
              }
            });
          } else {
            console.log("表单数据填写不正确");
          }
        });
      },
      // 删除指定权限
      delRights(row, rightId) {
        delRoleRight({ roleId: row.id, rightId: rightId }).then(res => {
          console.log(res);
          if (res.data.meta.status === 200) {
            this.$message.success("角色权限删除成功");
            this.initList();
          }
        });
      },
      // 展示角色授权树
      rolesRights(row) {
        // 接收当前角色的授权数据
        this.currentRole = row;
        console.log("泥猴，看树嘛");
        getRightsList({ type: "tree" }).then(res => {
          console.log(res);
          if (res.meta.status === 200) {
            this.treeData = res.data;
            this.rolesRightsDialogFormVisible = true;
            // 清空数组
            this.selectedRights.length = 0;
            // 填充树  选择已有权限即 挑出所有三级权限的id
            this.getRightsIds(row.children, this.selectedRights);
          }
        });
      },
      // 剝離權限的id，組成數組
      getRightsIds(data, arr) {
        data.forEach(val => {
          if (val.children && val.children.length !== 0) {
            val.children.forEach(valu => {
              if (valu.children && valu.children.length !== 0) {
                valu.children.forEach(value => {
                  arr.push(value.id);
                });
              }
            });
          }
        });
      },
      // 角色权限设置完成
      submitEditRoleRights() {
        let arr = this.$refs.tree.getCheckedNodes();
        // console.log(arr)
        var allIdArr = arr.map(item => item.pid + "," + item.id);
        // ES6数组去重  ...new Set(arr)
        var tempArr = allIdArr.join(",").split(",");
        // 展开arr 并且去除重复的项，形成新数组
        let ridsArr = [...new Set(tempArr)];
        console.log(ridsArr, "去重后");
        rolesGetRights({
          roleId: this.currentRole.id,
          rids: ridsArr.join(",")
        }).then(res => {
          console.log(res);
          if (res.data.meta.status === 200) {
            this.$message.success("角色重新授权成功");
            this.rolesRightsDialogFormVisible = false;
            this.initList();
          }
        });
      }
    }
  };
</script>
<style lang="scss" scoped>
  .el-margin {
    margin-bottom: 5px;
    margin-right: 5px;
  }
</style>
